package com.metacube.metaconnect.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.metacube.metaconnect.Service.CommentsService;

/**
 * Servlet implementation class InsertCommentServlet
 */
public class InsertCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public InsertCommentServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * insert the comment posted by user to database comments table
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int post_id = Integer.parseInt(request.getParameter("post_id"));

		if (request.getSession().getAttribute("emailId") != null) {
			String email = request.getSession().getAttribute("emailId")
					.toString();

			String comment = request.getParameter("comment");

			if (!comment.trim().equals(""))
				new CommentsService().insertComment(email, post_id, comment);

			if (request.getParameter("userEmail") == null)
				response.sendRedirect("home.jsp");
			else
				response.sendRedirect("OtherUserHome.jsp?userEmail="
						+ request.getParameter("userEmail"));
		} else
			response.sendRedirect("index.jsp");
	}

}
